<template>
  <div class="home-container">
    <van-nav-bar title="SheLife" fixed />
    
    <div class="content">
      <!-- 用户欢迎区域 -->
      <div class="welcome-section">
        <div class="user-info">
          <van-image
            round
            width="60"
            height="60"
            src="https://img.yzcdn.cn/vant/cat.jpeg"
          />
          <div class="user-text">
            <h3>你好，小美</h3>
            <p>今天是生理期的第 {{ cycleDay }} 天</p>
          </div>
        </div>
      </div>

      <!-- 功能模块卡片 -->
      <div class="feature-cards">
        <van-grid :column-num="2" :gutter="10">
          <van-grid-item @click="goToHealth">
            <div class="feature-card health-card">
              <van-icon name="chart-trending-o" size="32" color="#ee0a24" />
              <span class="feature-title">生理期管理</span>
              <span class="feature-desc">记录周期，预测经期</span>
            </div>
          </van-grid-item>
          
          <van-grid-item @click="goToHabits">
            <div class="feature-card habit-card">
              <van-icon name="checked" size="32" color="#07c160" />
              <span class="feature-title">习惯打卡</span>
              <span class="feature-desc">养成良好习惯</span>
            </div>
          </van-grid-item>
          
          <van-grid-item @click="goToSkincare">
            <div class="feature-card skincare-card">
              <van-icon name="flower-o" size="32" color="#7232dd" />
              <span class="feature-title">护肤记录</span>
              <span class="feature-desc">记录护肤历程</span>
            </div>
          </van-grid-item>
          
          <van-grid-item @click="goToSettings">
            <div class="feature-card settings-card">
              <van-icon name="setting-o" size="32" color="#323233" />
              <span class="feature-title">隐私设置</span>
              <span class="feature-desc">保护您的数据</span>
            </div>
          </van-grid-item>
        </van-grid>
      </div>

      <!-- 今日提醒 -->
      <div class="today-reminders">
        <van-cell-group title="今日提醒">
          <van-cell v-for="(reminder, index) in reminders" :key="index" :title="reminder.title" :value="reminder.value" />
        </van-cell-group>
      </div>
    </div>

    <!-- 底部导航 -->
    <van-tabbar v-model="activeTab" fixed>
      <van-tabbar-item icon="home-o" name="home">首页</van-tabbar-item>
      <van-tabbar-item icon="chart-trending-o" name="health">健康</van-tabbar-item>
      <van-tabbar-item icon="checked" name="habits">习惯</van-tabbar-item>
      <van-tabbar-item icon="user-o" name="profile">我的</van-tabbar-item>
    </van-tabbar>
  </div>
</template>

<script setup>
import { ref, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { userApi, menstrualCycleApi } from '@/api/services'
import { initMqttClient, subscribeTopic, unsubscribeTopic, publishMessage, disconnectMqtt } from '@/api/mqtt'

const router = useRouter()
const activeTab = ref('home')
const cycleDay = ref(12)
const loading = ref(false)
const userInfo = ref(null)
const cycleInfo = ref(null)
const reminders = ref([])

// 初始化数据
const initData = async () => {
  loading.value = true
  try {
    // 获取用户信息
    const userId = localStorage.getItem('userId') || '00000000-0000-0000-0000-000000000000'
    const userResponse = await userApi.getUserById(userId)
    if (userResponse) {
      userInfo.value = userResponse
    }
    
    // 获取生理周期信息
    const cyclesResponse = await menstrualCycleApi.getCyclesByUserId(userId)
    if (cyclesResponse && cyclesResponse.length > 0) {
      // 计算当前周期天数
      const latestCycle = cyclesResponse[0]
      const startDate = new Date(latestCycle.startDate)
      const today = new Date()
      const diffTime = Math.abs(today - startDate)
      const diffDays = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
      cycleDay.value = diffDays
      cycleInfo.value = latestCycle
    }
    
    // 设置提醒
    setReminders()
  } catch (error) {
    console.error('获取数据失败:', error)
  } finally {
    loading.value = false
  }
}

// 设置提醒
const setReminders = () => {
  reminders.value = [
    { title: '生理期预测', value: cycleInfo.value ? '还有 3 天' : '请记录周期' },
    { title: '护肤打卡', value: '待完成' },
    { title: '喝水提醒', value: '已完成 6/8 杯' }
  ]
}

// MQTT消息处理
const handleMqttMessage = (message) => {
  console.log('收到MQTT消息:', message)
  // 根据消息类型更新UI
  if (message.type === 'reminder') {
    // 更新提醒
    const index = reminders.value.findIndex(r => r.title === message.title)
    if (index !== -1) {
      reminders.value[index].value = message.value
    }
  } else if (message.type === 'cycle_update') {
    // 更新周期信息
    cycleDay.value = message.day
  }
}

// 初始化MQTT
const initMqtt = async () => {
  try {
    await initMqttClient()
    // 订阅用户专属主题
    const userId = localStorage.getItem('userId') || 'default'
    subscribeTopic(`shelife/user/${userId}/reminders`, handleMqttMessage)
    subscribeTopic(`shelife/user/${userId}/cycle_update`, handleMqttMessage)
    
    // 发布用户上线消息
    publishMessage(`shelife/user/${userId}/status`, {
      type: 'status',
      status: 'online',
      timestamp: new Date().toISOString()
    })
  } catch (error) {
    console.error('MQTT初始化失败:', error)
  }
}

const goToHealth = () => {
  router.push('/health')
}

const goToHabits = () => {
  router.push('/habits')
}

const goToSkincare = () => {
  router.push('/skincare')
}

const goToSettings = () => {
  router.push('/settings')
}

// 生命周期钩子
onMounted(() => {
  initData()
  initMqtt()
})

onUnmounted(() => {
  // 清理MQTT订阅
  const userId = localStorage.getItem('userId') || 'default'
  unsubscribeTopic(`shelife/user/${userId}/reminders`, handleMqttMessage)
  unsubscribeTopic(`shelife/user/${userId}/cycle_update`, handleMqttMessage)
  
  // 发布用户下线消息
  publishMessage(`shelife/user/${userId}/status`, {
    type: 'status',
    status: 'offline',
    timestamp: new Date().toISOString()
  })
})
</script>

<style scoped lang="scss">
.home-container {
  min-height: 100vh;
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  padding-bottom: 50px;
}

.content {
  padding: 60px 16px 70px;
}

.welcome-section {
  background: white;
  border-radius: 16px;
  padding: 20px;
  margin-bottom: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 15px;
}

.user-text {
  h3 {
    margin: 0;
    color: #333;
    font-size: 18px;
  }
  p {
    margin: 5px 0 0;
    color: #666;
    font-size: 14px;
  }
}

.feature-cards {
  margin-bottom: 20px;
}

.feature-card {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px;
  border-radius: 12px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transition: transform 0.3s ease;
  
  &:hover {
    transform: translateY(-2px);
  }
}

.feature-title {
  margin-top: 10px;
  font-size: 16px;
  font-weight: 500;
  color: #333;
}

.feature-desc {
  margin-top: 5px;
  font-size: 12px;
  color: #999;
}

.today-reminders {
  background: white;
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
</style>